﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Simple script that handles both the players projectiles
/// slightly different behaviour for each one ricochets off of obstacles 
/// while the other will pass through everything - it is set as a trigger in this instance.  
/// Could be split into two separate classes for neatness.
/// </summary>

public class BulletMove : MonoBehaviour
{
	public float speed;
    public bool Spin = false;
    void Awake() {        
		rigidbody2D.velocity = transform.right * speed;
        if(Spin) rigidbody2D.angularVelocity = Random.Range(-800,800);
        StartCoroutine(delayedDestroy(5.0f, gameObject));

        if(SpritePool != null && SpritePool.Count > 0) {
            GetComponent<SpriteRenderer>().sprite = SpritePool[Random.Range(0, SpritePool.Count)];
        }
	}
    
    bool Hit = false;
    Ai HitObj = null;

    public List<Sprite> SpritePool;

    void OnCollisionEnter2D(Collision2D other) {
        var bot = other.gameObject.GetComponent<Ai>();

        if(Hit == false) {
            Hit = true;
            HitObj = bot;
            StartCoroutine(delayedDestroy(0.5f, gameObject));
            if(bot != null) bot.damage(6.0f);
            rigidbody2D.velocity = rigidbody2D.velocity*0.75f + Random.insideUnitCircle*speed*0.5f;
        } else {
            //     Destroy(this);
        }
    }
    void OnTriggerEnter2D(Collider2D other) {
        var bot = other.gameObject.GetComponent<Ai>();
        if(bot != null) {
            bot.damage(40.0f);
            bot.rigidbody2D.AddForceAtPosition(rigidbody2D.velocity, transform.position);
        }
    }
    IEnumerator delayedDestroy(float delay, GameObject go) {
        yield return new WaitForSeconds(delay);
        Destroy(go);
    }
}
